import os
import random
import time

import eventlet
from flask import Flask

from config.logger_config import logger

app = Flask(__name__)
global_variable = random.randint(1,  1000)

def gf(name):
    logger.debug(f"invoke gf({name}) at {time.time()}")
    eventlet.sleep(3)  # 这里用eventlet的sleep代替耗时操作，也可以是实际的网络等待、文件读写等耗时操作
    return name

@app.route('/get-sync', methods=['GET'])
def hello2():
    worker_pid = os.getpid()  # 获取当前worker的PID
    logger.debug(f"global_variable:{global_variable}, get-sync api {time.time()} by worker PID:{worker_pid}")
    gf('张三')
    gf('李三')
    return f'Hello2, World! {time.time()}'

@app.route('/get-async', methods=['GET'])
def hello():
    worker_pid = os.getpid()  # 获取当前worker的PID
    logger.debug(f"global_variable:{global_variable}, get-async api {time.time()} by worker PID:{worker_pid}")
    g1 = eventlet.spawn(gf, '张三')
    g2 = eventlet.spawn(gf, '李三')
    value1 = g1.wait()
    value2 = g2.wait()
    logger.debug(f"get info {value1} {time.time()}")
    logger.debug(f"get info {value2} {time.time()}")
    return f'Hello, World! {time.time()} '
#gunicorn通过配置启动：gunicorn -c gunicorn_config_4_flask_eventlet_web.py flask_eventlet_web:app
if __name__ == '__main__':
    # app.run(host='0.0.0.0', port=5600)
    from eventlet import wsgi
    wsgi.server(eventlet.listen(("0.0.0.0", 5600)), app)